package xyz.zchao.blog.exception;

import org.springframework.ui.Model;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import xyz.zchao.blog.util.ResultCode;
import xyz.zchao.blog.util.ResultVO;

/**
 * 全局异常统一处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理参数校验错误异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResultVO<String>(ResultCode.VALIDATE_FAILED.getCode(), objectError.getDefaultMessage(), null);
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResultVO missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException e) {
        return new ResultVO<String>(ResultCode.MISSING_REQUEST_PARAMETER, null);
    }

    /**
     * 自定义异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(CustomizeException.class)
    public ResultVO<String> customizeException(CustomizeException e) {
        return new ResultVO<String>(e.getCode(), e.getMsg(), null);
    }

    /**
     * 其他异常
     * @param e
     * @return
     */
//    @ExceptionHandler(Exception.class)
//    @ResponseBody
//    public ResultVO<String> exHandler(Exception e){
//        return new ResultVO<String>(ResultCode.UNKNOWN_ERROR,e.getMessage());
//    }

}
